package com.linfeng.api.redis.listener;

import cn.hutool.core.util.StrUtil;
import com.linfeng.api.redis.config.RedisConfigProperties;
import com.linfeng.common.constant.ShopConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

/**
 * @author linfeng
 * @date 2021/1/13 13:55
 * 过期监听
 */
@Component
@Slf4j
@AllArgsConstructor
public class RedisKeyExpirationListener implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisConfigProperties redisConfigProperties;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<?> serializer = redisTemplate.getValueSerializer();
        String channel = String.valueOf(serializer.deserialize(message.getChannel()));
        String body = String.valueOf(serializer.deserialize(message.getBody()));

        if(StrUtil.format("__keyevent@{}__:expired", redisConfigProperties.getDatabase()).equals(channel)){
            //TODO：订单自动取消等监听过期事件处理
            if(body.contains(ShopConstants.REDIS_ORDER_OUTTIME_UNPAY)) {
                body = body.replace(ShopConstants.REDIS_ORDER_OUTTIME_UNPAY, "");
                log.info("body:{}",body);

            }

        }
    }
}
